package com.ruoyi.dr.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dr.domain.DrOwnerUnion;
import com.ruoyi.dr.domain.DrSampleSellAnalysis;
import com.ruoyi.dr.domain.DrSellDetails;
import com.ruoyi.dr.mapper.DrOwnerUnionMapper;
import com.ruoyi.dr.mapper.DrSellDetailsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dr.mapper.DrSampledataMapper;
import com.ruoyi.dr.domain.DrSampledata;
import com.ruoyi.dr.service.IDrSampledataService;

import javax.annotation.Resource;

/**
 * 寄样Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-14
 */
@Service
public class DrSampledataServiceImpl implements IDrSampledataService 
{
    private static final Logger log = LoggerFactory.getLogger(DrSampledataServiceImpl.class);

    @Autowired
    private DrSampledataMapper drSampledataMapper;

    @Resource
    private DrSellDetailsMapper drSellDetailsMapper;

    @Resource
    private DrOwnerUnionMapper ownerUnionMapper;

    /**
     * 查询寄样
     * 
     * @param id 寄样主键
     * @return 寄样
     */
    @Override
    public DrSampledata selectDrSampledataById(Long id)
    {
        return drSampledataMapper.selectDrSampledataById(id);
    }

    /**
     * 查询寄样列表
     * 
     * @param drSampledata 寄样
     * @return 寄样
     */
    @Override
    public List<DrSampledata> selectDrSampledataList(DrSampledata drSampledata)
    {
        return drSampledataMapper.selectDrSampledataList(drSampledata);
    }

    /**
     * 新增寄样
     * 
     * @param drSampledata 寄样
     * @return 结果
     */
    @Override
    public int insertDrSampledata(DrSampledata drSampledata)
    {
        return drSampledataMapper.insertDrSampledata(drSampledata);
    }

    /**
     * 修改寄样
     * 
     * @param drSampledata 寄样
     * @return 结果
     */
    @Override
    public int updateDrSampledata(DrSampledata drSampledata)
    {
        return drSampledataMapper.updateDrSampledata(drSampledata);
    }

    /**
     * 批量删除寄样
     * 
     * @param ids 需要删除的寄样主键
     * @return 结果
     */
    @Override
    public int deleteDrSampledataByIds(Long[] ids)
    {
        return drSampledataMapper.deleteDrSampledataByIds(ids);
    }

    /**
     *  交付数量，寄样数量，交付率，寄样天数，开始寄样日期，最后寄样日期
     *
     * */
    @Override
    public List<DrSampleSellAnalysis> sampleSellAnalysis(String userName) {
        DrOwnerUnion drOwnerUnion = new DrOwnerUnion();
        if(!StringUtils.equals(userName, "admin")) {
            drOwnerUnion.setOwner(userName);
        }
        List<DrOwnerUnion> drOwnerUnions = ownerUnionMapper.selectDrOwnerUnionList(drOwnerUnion);
        // 已有归属的达人id
        Set<String> awemeIdList = drOwnerUnions.stream()
                .map(DrOwnerUnion::getAwemeId)
                .collect(Collectors.toSet());
        String[] awemeIdArray = awemeIdList.toArray(new String[awemeIdList.size()]);
        // 交付数量
        Map<String, Map<String, String>> deliveryQuantityMap = drSampledataMapper.selectDeliveryQuantity(awemeIdArray);
        // 寄样数量
        List<DrSampleSellAnalysis> sampleStatistics = drSampledataMapper.getSampleStatistics(awemeIdArray);
        for (DrSampleSellAnalysis sampleStatistic : sampleStatistics) {
            Map<String, String> map = deliveryQuantityMap.get(sampleStatistic.getAwemeId());
            if (Objects.nonNull(map)) {
                sampleStatistic.setDeliveryQuantity(map.get("num"));
            } else {
                sampleStatistic.setDeliveryQuantity("0");
            }

            // 交付率 = 寄样数量/交付数量
            if(Objects.isNull(sampleStatistic.getDeliveryQuantity()) ||
                    StringUtils.equals(sampleStatistic.getDeliveryQuantity(), "0")){
                sampleStatistic.setDeliveryRate("0");
            } else if (StringUtils.equals(sampleStatistic.getSampleNum(), "0")) {
                if (StringUtils.equals(sampleStatistic.getDeliveryQuantity(), "0")) {
                    sampleStatistic.setDeliveryRate("0");
                } else {
                    sampleStatistic.setDeliveryRate("1");
                }
            } else {
                BigDecimal sampleNum = new BigDecimal(sampleStatistic.getSampleNum());
                BigDecimal deliveryQuantity = new BigDecimal(sampleStatistic.getDeliveryQuantity());
                BigDecimal divide = deliveryQuantity.divide(sampleNum, 2, RoundingMode.HALF_UP);
                sampleStatistic.setDeliveryRate(divide.toString());
            }

        }
        return sampleStatistics;
    }

    /**
     * 删除寄样信息
     * 
     * @param id 寄样主键
     * @return 结果
     */
    @Override
    public int deleteDrSampledataById(Long id)
    {
        return drSampledataMapper.deleteDrSampledataById(id);
    }

    @Override
    public String importSampledata(List<DrSampledata> sampledatas, String operName) {
        if (StringUtils.isNull(sampledatas) || sampledatas.size() == 0)
        {
            throw new ServiceException("导入寄样表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (DrSampledata sampledata : sampledatas) {
            String[] productSplit = sampledata.getProduct().split("id=");
            String[] productId = productSplit[1].split("&");
            //todo
            sampledata.setApplicant("沈晓欣");
            sampledata.setTzOwner("巨狮星选");
            sampledata.setProductId(productId[0]);
            try
            {
                // 验证是否存在这个用户
                DrSampledata s = drSampledataMapper.selectDrSampledataByDateAndAwemeId(sampledata);


                if (StringUtils.isNull(s)) {
                    Integer num = drSampledataMapper.selectByAwemeIdAndProductId(sampledata);
                    sampledata.setNum(num + 1);
                    drSampledataMapper.insertDrSampledata(sampledata);
//                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 条数据 导入成功");
                } else {
//                    BeanValidators.validateWithException(validator, user);
//                    checkUserAllowed(u);
//                    checkUserDataScope(u.getUserId());
//                    deptService.checkDeptDataScope(user.getDeptId());
//                    user.setUserId(u.getUserId());
//                    user.setUpdateBy(operName);
//                    userMapper.updateUser(user);
                    drSampledataMapper.updataByDateAndAwemeId(sampledata);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 条数据 更新成功");
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "条数据： 时间：" + sampledata.getTime() + "，抖音号：" + sampledata.getAwemeId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
